<template>
  <div class="spare-parts-config">
    <div class="config-type">
      <div class="config-name">备件类型配置</div>
        <div class="cascader-container">
          <div class="btn-container">
            <el-select v-if="!cascaderDisable" v-model="cascaderLevel" placeholder="请选择" @change="handleCascaderLevelChange">
              <el-option
                v-for="item in [1, 2, 3, 4, 5]"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-button v-if="cascaderDisable" style="float:right" type="primary" @click="editSpareType">编辑</el-button>
            <el-button v-if="!cascaderDisable" style="float:right"  type="primary" @click="handelSaveSpareType">保存</el-button>
            <el-button v-if="!cascaderDisable" style="float:right;margin-right:10px" @click="cancelSpareType">取消</el-button>
          </div>
          <CascaderConfig ref="cascader" :maxlength="20" :disabled="cascaderDisable"></CascaderConfig>
        </div>
    </div>
    <div v-for="(item, index) in configList" :key="index" class="config-type">
      <div class="config-name">{{ item.name }}</div>
      <el-table
        v-if="item.dataList && item.dataList.length"
        :data="item.dataList"
        max-height="300px"
      >
        <el-table-column label="名称" prop="typeName"></el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="{ row }">
            <span class="edit" @click="editConfig(item, row)">编辑</span>
            <span
              v-if="!row.isPreset"
              class="del"
              @click="deleteConfig(item.type, row)"
              >删除</span
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="add-config">
        <el-input
          :placeholder="item.placeholder"
          v-model="item.addName"
          clearable
        ></el-input>
        <el-button
          :class="{ 'add-cont': item.addName }"
          @click="item.addName ? addConfig(item) : ''"
          ><i class="el-icon-plus" />添加</el-button
        >
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Component, Ref, Vue } from 'vue-property-decorator'
import { commonAction } from '@/utils/common'
import { mutations } from '@/afterSales/views/spare/store/spareData'
// import CascaderConfig from '@/views/config/customerConfig/customerFields/components/cascader.vue'
import CascaderConfig from './cascaderConfig.vue'
@Component({
  name: 'sparePartsConfig',
  components: {
    CascaderConfig
  }
})
export default class SpareConfig extends Vue {
  @Ref() private readonly cascader: any
  private $message: any
  private $confirm: any
  private $prompt: any

  private configList: any = [
    {
      name: '出库类别配置',
      placeholder: '添加出库类型,若添加多个请以逗号(英文)分隔',
      type: 'spareOutStockType',
      dataList: []
    },
    {
      name: '入库类别配置',
      placeholder: '添加入库类型,若添加多个请以逗号(英文)分隔',
      type: 'spareInStockType',
      dataList: []
    },
    {
      name: '单位配置',
      placeholder: '添加单位,若添加多个请以逗号(英文)分隔',
      type: 'unitConfigs',
      dataList: []
    }
  ]

  private cascaderLevel: number = 1
  private cascaderDisable: boolean = true
  private originCascaderData: any = {}
  private originCascaderLevel: number = 1

  private editSpareType () {
    this.cascaderDisable = false
  }

  private cancelSpareType () {
    this.cascaderDisable = true
    this.cascader.group1 = JSON.parse(JSON.stringify(this.originCascaderData))
    this.cascader.setLevel(this.originCascaderLevel)
    this.cascaderLevel = this.originCascaderLevel
  }

  private handelSaveSpareType () {
    const spareType = this.cascader.group1[0]
    const postData = {
      configType: 'spareType',
      spareType
    }
    commonAction({ url: '/server-work/action/spareConfig/create', method: 'post', data: postData }).then(res => {
      if (res.success) {
        this.$message.success('保存成功')
        this.cascaderDisable = true
        this.getConfigData()
      }
    })
  }

  private handleCascaderLevelChange (val) {
    this.cascader.setLevel(val)
  }

  private addConfig (listRow: any) { // 添加配置
    const value = listRow.addName
    const updateConfig = {
      configType: listRow.type
    }
    updateConfig[listRow.type] = value
    commonAction({ url: '/server-work/action/spareConfig/create', method: 'post', data: updateConfig }).then(res => {
      if (res.success) {
        this.$message.success('添加成功')
        this.getConfigData()
        listRow.addName = '' // 清空添加的数据
      }
    })
  }

  private editConfig (item: any, row: any) { // 编辑配置数据
    const config: any = {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: row.typeName
    }
    this.$prompt('名称', `${item.name}修改`, config).then(({ value }) => {
      const editData = {
        configType: item.type
      }
      editData[item.type] = {
        id: row.id,
        typeName: value
      }
      commonAction({ url: '/server-work/action/spareConfig/update', method: 'post', data: editData }).then(res => {
        if (res.success) {
          this.$message.success('修改成功')
          this.getConfigData()
        }
      })
    })
  }

  private deleteConfig (type: string, row: any) { // 删除配置数据
    this.$confirm('确认删除该配置?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const delData = {
        configType: type
      }
      delData[type] = {
        id: row.id,
        typeName: row.typeName
      }
      commonAction({ url: '/server-work/action/spareConfig/delete', method: 'post', data: delData }).then(res => {
        if (res.success) {
          this.$message.success('删除成功')
          this.getConfigData()
        }
      })
    })
  }

  private getConfigData () { // 获取备件设置的数据
    commonAction({ url: '/server-work/action/spareConfig/list', method: 'get' }).then(res => {
      if (res.success) {
        const { spareTypeList, spareOutStockTypeList, spareInStockTypeList, unitConfig, spareTypeLength } = res.data
        mutations.setStateData('obj', 'allSpareTypeObj', this.formateSpareType([], spareTypeList))
        mutations.setStateData('arr', 'spareTypeList', this.formateOptions(res.data.spareTypeList) || [])
        mutations.setStateData('arr', 'spareOutStockTypeList', res.data.spareOutStockTypeList)
        mutations.setStateData('arr', 'spareInStockTypeList', res.data.spareInStockTypeList)
        mutations.setStateData('arr', 'unitList', res.data.unitConfig)
        if (!spareTypeList || !spareTypeList.length) {
          this.cascaderLevel = 1
          this.cascader.setLevel(1)
          this.originCascaderData = JSON.parse(JSON.stringify([[], [], [], [], []]))
        } else {
          this.cascader.group1 = this.getCascaderData(spareTypeList)
          this.originCascaderData = JSON.parse(JSON.stringify(this.cascader.group1))
          this.cascader.setLevel(spareTypeLength)
          this.cascaderLevel = spareTypeLength
          this.originCascaderLevel = this.cascaderLevel
        }
        const workList: any = [] // 工单
        spareOutStockTypeList.forEach((item, index) => {
          if (item.isPreset) {
            spareOutStockTypeList.splice(index, 1)
            workList.push(item)
          }
        })
        this.configList[0].dataList = workList.concat(spareOutStockTypeList)
        this.configList[1].dataList = spareInStockTypeList
        this.configList[2].dataList = unitConfig
      }
    })
  }

  private formateSpareType (result: any[], val: any[]) {
    val.forEach(item => {
      result.push(item)
      if (Array.isArray(item.children) && item.children.length) {
        this.formateSpareType(result, item.children)
      }
    })
    return result
  }

  private formateOptions (val) {
    if (val) {
      val.forEach(item => {
        if (item.children) {
          item.children = this.formateOptions(item.children)
        }
      })
      const arr = val.filter(item => item.isDelete === 0)
      if (arr.length) {
        return arr
      } else {
        return null
      }
    }
  }

  private getCascaderData (val: any[]) {
    const formatKey = (value: any[]) => {
      return value.map(item => {
        item.key = item.id
        item.value = item.typeName
        if (Array.isArray(item.children) && item.children.length) {
          item.children = formatKey(item.children)
        }
        return item
      })
    }
    let level1: any[] = []
    let level2: any[] = []
    let level3: any[] = []
    let level4: any[] = []
    let level5: any[] = []
    level1 = formatKey(val)
    const level1Child = level1.find(item => item.isDelete === 0)
    level2 = formatKey(level1Child && level1Child.children ? level1Child.children : [])
    const level2Child = level2.find(item => item.isDelete === 0)
    level3 = formatKey(level2Child && level2Child.children ? level2Child.children : [])
    const level3Child = level3.find(item => item.isDelete === 0)
    level4 = formatKey(level3Child && level3Child.children ? level3Child.children : [])
    const level4Child = level4.find(item => item.isDelete === 0)
    level5 = formatKey(level4Child && level4Child.children ? level4Child.children : [])
    const result: any[] = [[], [], [], [], []]
    result[0] = level1
    result[1] = level2
    result[2] = level3
    result[3] = level4
    result[4] = level5
    return result
  }

  private mounted () {
    this.getConfigData()
  }
}

</script>
<style lang="stylus" scoped>
.spare-parts-config
  padding 24px 24px 0
  border-radius 10px
  height 100%
  overflow auto
  box-sizing border-box
  margin 0 2px 2px 0
  border 1px solid #ecf0f3
  box-shadow 0px 0px 4px 0px #e0e6f0,0px 1px 4px 0px #e0e6f0
  .config-type
    border-bottom 1px solid #E7E9ED
    margin-bottom 24px
    .cascader-container
      line-height 40px
      .btn-container
        height 40px
      /deep/.urlList
        flex 1
      /deep/.urlList:first-child
        margin 5px 5px 5px 0
    &:last-child
      border-bottom 0
      margin-bottom 0
    .config-name
      font-family PingFang SC
      font-weight 600
      color #303753
      margin-bottom 15px
      .cascader-container
        float right
    .el-table
      font-size 12px
    .edit
      color #008cee
      cursor pointer
      margin-right 16px
    .del
      color #fc6c5c
      cursor pointer
    .add-config
      margin 12px 0 24px
      display flex
      .el-input
        width 500px
        margin-right 16px
      .el-button
        width 70px
        height 32px
        border 1px solid #008bee
        color #008bee
        cursor not-allowed
        .el-icon-plus
          margin-right 5px
          color #008BEE
      .add-cont
        color #fff
        background #008bee
        cursor pointer
        .el-icon-plus
          margin-right 5px
          color #fff
</style>
